package com.xdja.netty.handler.inbound;

import com.xdja.netty.conf.HttpManager;
import com.xdja.netty.util.ResourceUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.FileRegion;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.handler.codec.http.*;

import java.io.File;
import java.nio.file.WatchKey;
import java.util.List;

/**
 * description
 *
 * @author zk
 * @since 2018/7/23
 */
public class FilterDecoder extends MessageToMessageDecoder<HttpManager.Entry<HttpRequest, HttpContent>> {

    @Override
    protected void decode(ChannelHandlerContext ctx, HttpManager.Entry<HttpRequest, HttpContent> msg, List<Object> out) throws Exception {
        String url = msg.getHttpRequest().uri().contains("?") ? msg.getHttpRequest().uri().substring(0, msg.getHttpRequest().uri().indexOf("?")) : msg.getHttpRequest().uri();
        if (url.equals("/")) {
            String htmlContent = ResourceUtil.getResourceContent("index.html");
            HttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
                    Unpooled.wrappedBuffer(htmlContent.getBytes()));
            httpResponse.headers().set("transfer-encoding", "trunked");
            httpResponse.headers().set("content-type", "text/html;charset=utf-8");
            ctx.channel().writeAndFlush(httpResponse).addListener(ChannelFutureListener.CLOSE);
        } else if (url.equals("/s")) {
            //add mapping
            out.add(msg);
        } else {
            //display url
            out.add(url);
        }
    }
}
